<template>
  <n-modal v-model:show="isVisible" title="客户订单" preset="dialog" @close="onClose" style="height: 660px;width: 700px">
    <n-form @submit.prevent="handleSubmit" label-width="120px" class="form-container" style="margin-left: 60px">
      <div class="form-row" style="margin-top: 20px">
        <n-form-item label="订单状态：" path="status">
          <n-select
              v-model:value="form.status"
              style="width:250px"
              size="small"
              :options="statusOptions"
              filterable
          >
          </n-select>
        </n-form-item>
        <n-form-item label="产品：" path="storeCommodityId" style="margin-left: 20px;width: 250px">
          <n-select
              v-model:value="form.storeCommodityId"
              style="width:250px"
              size="small"
              :options="storeCommodity"
              filterable
              disabled
          >
          </n-select>
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="数量：" path="quantity"  style="width: 250px">
          <n-input v-model:value="form.quantity" placeholder="请输入产品数量" disabled/>
        </n-form-item>
        <n-form-item label="金额：" path="price" style="margin-left: 20px;width: 250px">
          <n-input v-model:value="form.price" placeholder="请输入订单金额" disabled/>
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="币种：" path="currency" style="width: 250px">
          <n-input v-model:value="form.currency" placeholder="请输入交易币种" disabled/>
        </n-form-item>
        <n-form-item label="店铺：" path="shopId" style="margin-left: 20px;width: 250px">
          <n-select
              v-model:value="form.shopId"
              style="width:250px"
              size="small"
              :options="shops"
              filterable
              disabled
          >
          </n-select>
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="物流商：" path="logisticsProviderId" style="width: 250px">
          <n-select
              v-model:value="form.logisticsProviderId"
              style="width:250px"
              size="small"
              :options="logisticsProviders"
              filterable
              disabled
          >
          </n-select>
        </n-form-item>
        <n-form-item label="客户：" path="customerId" style="margin-left: 20px;width: 250px">
          <n-select
              v-model:value="form.customerId"
              style="width:250px"
              size="small"
              :options="customers"
              filterable
              disabled
          >
          </n-select>
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="客户电话：" path="customerPhone" style="width: 250px">
          <n-input v-model:value="form.customerPhone" placeholder="请输入客户电话" disabled/>
        </n-form-item>
        <n-form-item label="促销活动：" path="salePromotionId" style="margin-left: 20px;width: 250px">
          <n-select
              v-model:value="form.salePromotionId"
              style="width:250px"
              size="small"
              :options="salePromotions"
              filterable
              disabled
          >
          </n-select>
        </n-form-item>
      </div>

      <div class="form-row">
        <n-form-item label="仓库：" path="customerAddress" style="width: 250px">
            <n-input v-model:value="form.storeName" disabled/>
        </n-form-item>
        <n-form-item label="客户地址：" path="customerAddress" style="margin-left: 20px;width: 250px">
          <n-input v-model:value="form.customerAddress" placeholder="请输入客户地址" disabled/>
        </n-form-item>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-row" style="margin-left: -65px">
        <n-form-item>
          <n-button type="primary" native-type="submit" @click="handleSubmit">提交</n-button>
        </n-form-item>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>
import {ref, watch} from 'vue';
import {useUserStore} from "@/store/index.js";
import api from '@/api/admin.js'
import {List} from "echarts";

const userStore = useUserStore()
const id = userStore.getId();
const option = ref([
])
function handleChange(value) {
}
const emit = defineEmits(['updatePage'])
const props = defineProps({
  show1: {
    type: Boolean,
    required: true,
  },
  onClose: {
    type: Function,
    required: true,
  },
  option: {
    type: List,
    require: true
  },
  storeCommodity: {
    type: Array,
    required: true
  },
  shops: {
    type: Array,
    required: true
  },
  logisticsProviders: {
    type: Array,
    required: true
  },
  customers: {
    type: Array,
    required: true
  },
  salePromotions: {
    type: Array,
    required: true
  },
  attribute: {
    type: Object,
    required: true,
  },
  statusOptions: {
    type: Array,
    required: true
  }
});

const isVisible = ref(props.show1);
watch(() => props.show1, (newVal) => {
  isVisible.value = newVal;
  if (newVal) {
    // 当对话框显示时，将传递过来的属性值填充到表单中
    form.value = { ...props.attribute };
  }
});
const form = ref({
  status: '',
  storeCommodityId: null,
  quantity: '',
  price: '',
  currency: '',
  shopId: null,
  logisticsProviderId: null,
  customerId: null,
  customerPhone: '',
  salePromotionId: null,
  customerAddress: '',
  storeId: '',
  storeName: ''
});
// 获取当前时间并格式化的函数
function getCurrentFormattedTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
const handleSubmit = async () => {
  try {
    if (form.value.status === '已完成') {//判断库存够不够
      const res2 = await api.addOutboundDocument( //出库
          {
            ...form.value,
            adminId: id,
            id:"",
            type:"outbound",
            objectId: id,
            price:form.value.price,
            quantity:form.value.quantity
          }
      )
      if (res2.code === 200) {
        emit("updatePage")
      }
      else {
        $message.error(res2.message)
      }
      const res1 = await api.addFinanceReceipt(
          {
            ...form.value,
            orderType: "customer_order",
            type: "in",
            id:"",
            adminId:id,
            createTime: props.attribute.createTime,
            orderId:props.attribute.id,
            endTime: getCurrentFormattedTime(),
          }
      )
      if (res1.code === 200) {
        emit("updatePage")
      } else {
        $message.error(res1.message)
      }
      const res3 = await api.updateByCustomerId(
          {
            params:
                {
                  ...form.value,
                  customerOrderId: props.attribute.id,
                }
          }
      )
      if (res3.code === 200) {
        emit("updatePage")
      } else {
        $message.error(res1.message)
      }
    }
    const res = await api.updateCustomerOrder(
        {
          ...form.value,
          adminId: id,
        }
    )
    if(res.code === 200) {
      emit("updatePage")
    }
    else {
      $message.error(res.message)
    }
  } catch (err) {
    $message.error("修改失败！")
  }finally{
    clear()
    props.onClose();
  }
};
const clear = () => {
  form.value.status = ""
  form.value.storeCommodityId = null
  form.value.quantity = ""
  form.value.currency = ""
  form.value.shopId = null
  form.value.logisticsProviderId = null
  form.value.customerId = null
  form.value.customerPhone = ""
  form.value.salePromotionId = null
  form.value.customerAddress = ""
  form.value.storeId = ""
}
</script>

<style scoped>
.form-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  position: relative;
}

.form-row {
  display: flex;
  align-items: center;
  width: 100%;
}

.form-row > n-form-item {
  flex: 1;
}

.submit-row {
  justify-content: center;
  display: flex;
  width: 100%;
}
</style>
